<template>
    <el-upload
            ref="upload"
            action="#"
            :file-list="fileUploadList"
            :auto-upload="false"
            :http-request="uploadMethod"
            :before-remove="beforeRemove"
            :on-remove="onRemove"
            :with-credentials="true"
            :on-success="onSuccess"
            :on-error="onError"
            multiple
    >
        <el-button slot="trigger" class="file-input-btn" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="uploadFiles">上传</el-button>
        <div slot="tip" >点击上传后可以在当前页面查看进度,文件将会在后台传输，请不要刷新页面。</div>
    </el-upload>
</template>

<script>
    const fileBuffer = [];
    export default {
        name: "FileUpload",
        props:{
            uploadMethod:Function,
            onSuccess:Function
        },
        data(){
            return{
                fileUploadList:fileBuffer,
            }
        },
        methods:{
            uploadFiles(){
                this.$refs.upload.submit();
            },
            onRemove(file){
                if(file.raw.cancelSource){
                    file.raw.cancelSource.cancel();
                }
            },
            beforeRemove(file){
                if(file.status!=="uploading")return true;
                return new Promise((resolve, reject) => {
                    this.$confirm(`文件${file.name}正在上传中，是否要取消上传？`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        resolve();
                    }).catch(() => {
                        reject();
                    });
                });
            },
            onError(err, file){
                let e = err;
                if(err.response&&err.response.data) e = err.response.data;
                this.$notify.error({
                    title: `${file.name}上传失败！`,
                    message: e.message
                });
            }
        }
    }
</script>

<style>
.file-input-btn + .el-upload__input{
    display: none;
}
</style>